<?php
namespace app\admin\controller;
use app\admin\controller\Common;
use app\service\roomService;
use app\service\roominfoService;
use think\facade\Db;
use think\facade\View;
use think\Log;
class Room extends Common{
   
    //下拉菜单
    public function fetchdata() {
        $type = request()->post('type');
        switch($type) {
            case 1:
                $community_id = request()->post('community_id');
                $group = array_unique((new roominfoService())->groupList($community_id));
                return array_values($group);
            case 2:
                $community_id = request()->post('community_id');
                $group = request()->post('group');
                $building = array_unique((new roominfoService())->buildingList($community_id,$group));
                return array_values($building);
            case 3:
                $community_id = request()->post('community_id');
                $group = request()->post('group');
                $building = request()->post('building');
                $unit = array_unique((new roominfoService())->unitList($community_id,$group,$building));
                return array_values($unit);
            case 4:
                $community_id = request()->post('community_id');
                $group = request()->post('group');
                $building = request()->post('building');
                $unit = request()->post('unit');
                $room = array_unique((new roominfoService())->roomList($community_id,$group,$building,$unit));
                return array_values($room);
            default:
                return json(['info' => '查询错误']);
        }
    }
    //房屋管理
    //显示小区房屋信息
    public function roomList(){
        //查询小区信息
        $com = $this->pidTokenId();
        //$whe['id'] = array('in',$com['community_id']);
        $whe=[];
        $whe[] =["id","in",$com['community_id']];
        $communitylist = (new roominfoService())->communityList($whe);
        //Log::write($communitylist,"community");
        $community_id = $com['community_id'];
        View::assign('communitylist',$communitylist);
        //查询
        $data = request()->get();
        // dump($data);exit();
        if (!empty($data['community_id'])){
            $groups = array_unique((new roominfoService())->groupList($data['community_id']));
            View::assign('groups', array_values($groups));
            // dump($data['group']);
            if (!empty($data['group'])) {
                $buildings = array_unique((new roominfoService())->buildingList($data['community_id'],$data['group']));
                View::assign('buildings', array_values($buildings));
                // dump($buildings);exit();
                if (!empty($data['building'])) {
                    $units = array_unique((new roominfoService())->unitList($data['community_id'], $data['group'],$data['building']));
                    View::assign('units', array_values($units));
                    if(!empty($data['unit'])){
                        $rooms = array_unique((new roominfoService())->roomList($data['community_id'], $data['group'],$data['building'],$data['unit']));
                        View::assign('rooms', array_values($rooms));
                    }
                }
            }
        }
        $where=array();
        //var_dump($data);
        if (!empty($data)){
            if(!empty($data['community_id'])){
                $where['community_id'] = $data['community_id'];//小区名称
            }else{
                $where['community_id'] = "";
            }
            if(!empty($data['group'])){
                $where['group'] = $data['group'];//组团
            }else{
                $where['group'] = "";
            }
            if(!empty($data['building'])){
                $where['building'] = $data['building'];//楼栋
            }else{
                $where['building'] = "";
            }
            if(!empty($data['unit'])){
                $where['unit'] = $data['unit'];//单元
            }else{
                $where['unit'] = "";
            }
            if(!empty($data['room'])){
                $where['room'] = $data['room'];//房号
            }else{
                $where['room'] = "";
            }
            if(!empty($data['name'])){
                $where['name'] = $data['name'];//姓名
            }else{
                $where['name'] = "";
            }
            if(!empty($data['phone'])){
                $where['phone'] = $data['phone'];//电话
            }else{
                $where['phone'] = "";
            }
            View::assign('where',$where);   

        }
        $where = array_filter($where);
        //var_dump($where);die;
        $export = $where;
        $export = json_encode($export);
        $export = str_replace("\"","|",$export);
        View::assign('export',$export);

        $page = request()->has('page') ? request()->get('page') : 1;
        //查询房屋条数

        $number =(new roominfoService())->roomWhereNumber($community_id,$where);

        View::assign('number',$number);
        //查询房屋信息
        $roomlist = (new roominfoService())->roomWhereList($community_id,$page,$where);
        foreach ($roomlist as $key => $value) {
            
        }
        if($number!="0"){
            foreach($roomlist as $room){
                //根据小区编号查询小区名称
                $room['num'] = Db::table("personnel")->where("room_id",$room["id"])->count();
                //数据从新存入数组
                $list[] = $room;
                View::assign('list',$list);
            }
        }else{
            View::assign('list',$roomlist);
        }
        
        View::assign('roomlist',$roomlist);
        foreach ($data as $k => $v) {
            View::assign($k, $v);
        }

        return View::fetch('room_list');
    }
    //添加小区房屋信息
    public function roomAdd(){
        //查询小区信息
        $com = $this->pidTokenId();
        $where['id'] = array('in',$com['community_id']);
        $communitylist = (new roominfoService())->communityList($where);
        View::assign('communitylist',$communitylist);

        if(request()->isPost()){
            //获取表单数据
            $data = request()->post();
            //判断房屋是否重复
            $info = (new roominfoService())->roominfoName($data['community_id'],$data['group'],$data['building'],$data['unit'],$data['room']);
            $communityinfo=Db::table("community")->where("id",$data["community_id"])->find();
            if($info){
                $this->error('房屋已存在');
            }
            $data['community_name']=$communityinfo["name"];
            $data['time'] = time();
            //将数据插入数据库
            $result = (new roominfoService())->roominfoAdd($data);
            //判断数据是否插入成功
            if($result){
                $this->success('添加房屋成功',url('roomAdd'));
            }else{
                $this->error('添加房屋失败',url('roomAdd'));
            }
        }else{
            return View::fetch('room_add');
        }
    }
    
    //修改小区房屋信息
    public function roomEdit(){
        //查询小区信息
        $com = $this->pidTokenId();
        $where['id'] = array('in',$com['community_id']);
        $communitylist = (new roomService())->communityList($where);
        View::assign('communitylist',$communitylist);
        
        if(request()->isGet()){
            $id = request()->param('id');
            if(!isset($id) && empty($id)){
                $this->error('房屋不存在');
            }
            //查询房屋数据
            $info = (new roominfoService())->roominfoIdList($id);
            View::assign('info',$info);
            return View::fetch('room_edit');
        }else{
            //获取表单数据
            $data = request()->post();
            $info["name"]=$data["name"];
            $info["phone"]=$data["phone"];
            //$info["room"]=$data["room"];
            $info["id"]=$data["id"];

            //将修改的数据插入数据库
            $result = (new roominfoService())->roominfoEdit($info);
            //判断数据是否插入成功
            if($result){
                $this->success('修改房屋信息成功',url('roomList'));
            }else{
                $this->error('修改房屋信息失败',url('roomEdit'));
            }
        }
    }
   
    public function roomDel(){
        $validate = $this->validate(request()->param(),[
			'id'	=>	'require'
		]);
		if($validate !== true){
			$this->error($validate);
        }
        $id = request()->param('id');
        if (strpos($id, ',')) {
            $arr = explode(',', $id);
            $info = (new roomService())->checkRoomInfo($arr);
            if (count($info) != count($arr)) {
                return json(['info' => '房屋信息不完整']);
            }
            foreach($info as $inf){
                //判断房屋下是否有人员是否能删除
                $userinfo=Db::table("personnel")->where("room_id",$inf["id"])->find();
                if(!empty($userinfo)){
                    return json(['info' => '请先删除该房屋下的用户']);
                }

                $result =  (new roomService())->roomDel($inf['id']);  
            }
        }else{
            //判断是否存在该数据
            $info = (new roomService())->roomId($id);
            if(empty($info)){
                $this->error('该房屋不存在');
            }
            $userinfo=Db::table("personnel")->where("room_id",$id)->find();
            if(!empty($userinfo)){
                return json(['info' => '请先删除该房屋下的用户']);
            }
            $result =  (new roomService())->roomDel($id);
        }
        if($result){
            $this->success('删除成功',url('roomList'));
		}else{
            $this->success('删除失败',url('roomList'));
		}
    }
    //通过Excel批量添加房屋信息 
    public function roomExcel(){
        if(request()->isPOST()){
            //上传excel文件
            $file = request()->file('myfile');
            //移到/public/excel/下
            $info = $file->move(ROOT_PATH.'public'.DS.'excel');
            //上传文件成功
            if ($info) {
                //引入PHPExcel类
                vendor('PHPExcel.PHPExcel.Reader.Excel2007');
                //获取上传后的文件名
                $fileName = $info->getSaveName();
                //文件路径
                $filePath = dir(getcwd())->path.'/excel/'.$fileName;
                //判断文件格式，实例化相应的PHPExcel类，读取excel文件
                $extension = strtolower( pathinfo($fileName, PATHINFO_EXTENSION));
                if ($extension =='xlsx' || $extension =='xls') {
                    $objReader = new \PHPExcel_Reader_Excel2007();
                    $objPHPExcel = $objReader ->load($filePath);
                } else if ($extension=='csv') {
                    $objReader = new \PHPExcel_Reader_CSV();
                    //默认输入字符集
                    $objReader->setInputEncoding('GBK');
                    //默认的分隔符
                    $objReader->setDelimiter(',');
                    //载入文件
                    $objPHPExcel = $objReader ->load($filePath);
                }else{
                    $this->success('文件格式错误',url('billExcel'));
                }  
                //读取excel文件中的第一个工作表
                $sheet = $objPHPExcel->getSheet(0);
                $allRow = $sheet->getHighestRow();  //取得总行数
                //$allColumn = $sheet->getHighestColumn();  //取得总列数
                //从第三行开始插入，第一行是列名
                for ($j=2; $j <= $allRow; $j++) {
                    $data['community_name']=$objPHPExcel->getActiveSheet()->getCell("A".$j)->getValue();
                    $communityinfo=Db::table("community")->where("name",$data['community_name'])->find();
                    if(empty($communityinfo)){
                        echo "第".$j."小区名称不存在<br/>";
                        exit;
                    }
                    $data["community_id"]=$communityinfo["id"];
                    $data['group']=$objPHPExcel->getActiveSheet()->getCell("B".$j)->getValue();
                    $data['building']=$objPHPExcel->getActiveSheet()->getCell("C".$j)->getValue();
                    $data['unit']=$objPHPExcel->getActiveSheet()->getCell("D".$j)->getValue();
                    $data['room']=$objPHPExcel->getActiveSheet()->getCell("E".$j)->getValue();
                    //业主姓名
                    $data['name'] = $objPHPExcel->getActiveSheet()->getCell("F".$j)->getValue();
                    //业主电话
                    $data['phone'] = $objPHPExcel->getActiveSheet()->getCell("G".$j)->getValue();

                    $data['time'] = time();

                    $data = array_filter($data);
                    $number = count($data);
                    $numbers = 9;
                    if($number == $numbers){
                        //数据插入到数据库并返回主键id
                        //判断房屋是否重复
                        $roomname = (new roominfoService())->roominfoName($data['community_id'],$data['group'],$data['building'],$data['unit'],$data['room']);
                        
                        if($roomname){
                            echo "第".$j."行房间号重复，导入失败！<br/>";
                        }else{
                            $last_id = (new roomService())->roomExcelAdd($data); 
                            //判断数据是否插入成功
                            if ($last_id) {
                                echo "第".$j."行导入成功，room表第:".$j."条！<br/>";
                            }else{
                                echo "第".$j."行导入失败！<br/>";
                            } 
                        }
                    }else{
                        echo "第".$j."行数据不完整，导入失败！<br/>";
                    }
                    //
                }
                echo "结束";
            }else{
                $this->success('上传文件失败',url('roomExcel'));
            }
        }else{
            return View::fetch('room_excel');
        }
    }
    
     //导出房屋到Excel
    public function roomExportExcel(){
        $com = $this->pidTokenId();
        $whe['id'] = array('in',$com['community_id']);
       
        $community_id = $com['community_id'];
        
        //获取账单数据
        $id = request()->param('id');
        $export = request()->param('export');
        $export = str_replace("|","\"",$export);
        if(!empty($id)){
            $id = explode(',',request()->param('id'));
            $roomlist = (new roominfoService())->checkRoomInfo($id);
            if(count($roomlist) != count($id)){
                return json(['error' => '房屋信息不完整']);
            }
        }else{
            //查询小区信息
            $com = $this->pidTokenId();
            $whe['community_id'] = array('in',$com['community_id']);
            
            $community_id = $com['community_id'];
            $where = json_decode($export,true);
           
            $roomlist = Db::name('room')->where('community_id', 'in', $community_id)->where($where)->order('id asc')->select();
            if(empty($roomlist)){
                return json(['error' => '没有账单数据']);
            }
        }
        //设置表头
        //引入PHPExcel类
        vendor('PHPExcel.PHPExcel.Reader.Excel2007');
        $objPHPExcel = new \PHPExcel();
        //设置表头
        $objPHPExcel->setActiveSheetIndex(0)
        ->setCellValue('A1', '小区名称')
        ->setCellValue('B1', '组团')
        ->setCellValue('C1', '楼栋')
        ->setCellValue('D1', '单元')
        ->setCellValue('E1', '房号')
        ->setCellValue('F1', '业主姓名')
        ->setCellValue('G1', '业主电话')
        ;

        $count = count($roomlist);  //计算有多少条数据
        for ($i=2; $i <= $count+1; $i++) {
            //根据小区ID查询小区名称
           
            $objPHPExcel->getActiveSheet()->setCellValue('A' . $i, $roomlist[$i-2]["community_name"]);
            $objPHPExcel->getActiveSheet()->setCellValue('B' . $i, $roomlist[$i-2]['group']);
            $objPHPExcel->getActiveSheet()->setCellValue('C' . $i, $roomlist[$i-2]["building"]);
            $objPHPExcel->getActiveSheet()->setCellValue('D' . $i, $roomlist[$i-2]["unit"]);
            $objPHPExcel->getActiveSheet()->setCellValue('E' . $i, $roomlist[$i-2]["room"]);
            $objPHPExcel->getActiveSheet()->setCellValue('F' . $i, $roomlist[$i-2]["name"]);
            $objPHPExcel->getActiveSheet()->setCellValue('G' . $i, $roomlist[$i-2]["phone"]);

            
        }
        $objPHPExcel->getActiveSheet()->setTitle('房屋信息');      //设置sheet的名称
        $objPHPExcel->setActiveSheetIndex(0);                   //设置sheet的起始位置
        $objWriter = \PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');   //通过PHPExcel_IOFactory的写函数将上面数据写出来
        $PHPWriter = \PHPExcel_IOFactory::createWriter( $objPHPExcel,"Excel2007");
        header('Content-Disposition: attachment;filename="房屋信息.xls"');
        header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
        $PHPWriter->save("php://output"); //表示在$path路径下面生成demo.xlsx文件
    }
}